package com.top.ruizhong.main.host

import android.graphics.Typeface
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ConvertUtils
import com.module.lemlin.LoadingDialog
import com.module.lemlin.custom.SpacingItemDecoration
import com.module.lemlin.mode.ViewModeFragment
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.top.ruizhong.R
import com.top.ruizhong.entity.VideoDraft
import com.top.ruizhong.main.host.adpter.VideoWorksAdapter
import com.top.ruizhong.main.video.VideoEditingActivity
import com.top.ruizhong.mode.vm.UserViewModel
import com.top.ruizhong.popup.DialogHintPopup
import kotlinx.android.synthetic.main.fragment_main_works.*

class MainWorksFragment : ViewModeFragment<UserViewModel>() {


    companion object {
        private const val EXTRA_NAME_STATUS = "EXTRA_NAME_STATUS"
        fun newInstance(status: Int): MainWorksFragment {
            val bundle: Bundle = Bundle().apply {
                putInt(EXTRA_NAME_STATUS, status)
            }
            return MainWorksFragment().apply { arguments = bundle }
        }
    }

    private val videoWorksAdapter = VideoWorksAdapter()

    private var mVideoDraftItem: VideoDraft? = null

    private val deleteHintPopup: DialogHintPopup by lazy {
        DialogHintPopup(context = requireContext(),
            onConfirm = {
                mVideoDraftItem?.let {
                    viewModel.videoDelete(videoIds = it.id.toString())
                }
                deleteHintPopup.dismiss()
            },
            onCancel = {
                deleteHintPopup.dismiss()
            })
    }

    private val reasonHintPopup: DialogHintPopup by lazy {
        DialogHintPopup(context = requireContext(),
            onConfirm = {
                reasonHintPopup.dismiss()
            },
            onCancel = {
                reasonHintPopup.dismiss()
            })
    }

    override fun viewModel(): UserViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.fragment_main_works

    override fun initView() {
        rvWorksBody.apply {
            val decoration = SpacingItemDecoration(
                vGap = ConvertUtils.dp2px((15f)),
                hGap = ConvertUtils.dp2px((15f))
            )
            addItemDecoration(decoration)
        }.adapter = videoWorksAdapter.apply {
            status = arguments?.getInt(EXTRA_NAME_STATUS, 0) ?: 0
        }

        videoWorksAdapter.setOnItemChildClickListener { _, view, position ->
            val itemData: VideoDraft = videoWorksAdapter.getItem(position).apply {
                mVideoDraftItem = this
            }
            if (view.id == R.id.tvWorksDelete) {
                deleteHintPopup.setTextTitle("提示")
                    .setTextMessage("确定删除视频内容，不可修复")
                    .setTextCancel("取消")
                    .setTextConfirm("删除")
                    .showPopupWindow()
            } else if (view.id == R.id.tvWorksReason) {
                reasonHintPopup.isTextCancelGone(isGone = true)
                    .setTextTitle("提示")
                    .setTextMessage(itemData.reject_reason)
                    .setTextConfirm("好的")
                    .showPopupWindow()
            } else if (view.id == R.id.tvWorksEdit) {
                VideoEditingActivity.openModify(
                    activity = requireActivity(), videoDraft = itemData
                )
            }
        }


        //下拉刷新监听
        mSmartRefreshLayout.setOnRefreshListener {
            initData(isLoadMore = false)
        }
        //加载更多刷新监听
        mSmartRefreshLayout.setOnLoadMoreListener {
            initData(isLoadMore = true)
        }
    }

    override fun initData() {
        initData(isLoadMore = false)
    }

    private fun initData(isLoadMore: Boolean) {
        val status: Int = arguments?.getInt(EXTRA_NAME_STATUS, 0)
            ?: return
        viewModel.userMyVideos(status, isLoadMore)
    }

    override fun initViewMode() {

        viewModel.videoDraftLiveData.observe(this as LifecycleOwner, Observer { response ->
            val status: Status = responseStatus1LiveData(response.status, response.throwable)
            if (status != Status.SUCCESS)
                return@Observer
            val isLoadMore: Boolean = response.httpData?.loadMore ?: false
            val videoDrafts: MutableList<VideoDraft> =
                response.httpData?.data?.data ?: mutableListOf()
            if (videoDrafts.isNullOrEmpty()) {
                videoWorksAdapter.setEmptyView(createErrorView(hint = "暂无数据"))
            }
            if (isLoadMore) {
                videoWorksAdapter.addData(videoDrafts)
            } else {
                videoWorksAdapter.setNewInstance(videoDrafts)
            }
            if (videoDrafts.size < viewModel.limit) {
                videoWorksAdapter.setFooterView(createFooterView())
                mSmartRefreshLayout.setEnableLoadMore(false)
            } else {
                videoWorksAdapter.removeAllFooterView()
                mSmartRefreshLayout.setEnableLoadMore(true)
            }
        })

        viewModel.videoDeleteLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (responseStatus2LiveData(response.status, response.throwable) != Status.SUCCESS)
                return@Observer
            initData(isLoadMore = false)
        })
    }


    private fun responseStatus1LiveData(status: Status, throwable: Throwable?): Status {
        if (status == Status.START) {
            videoWorksAdapter.setEmptyView(createLoadingView())
        } else if (status == Status.FAILURE) {
            mSmartRefreshLayout.finishRefresh((false))
            videoWorksAdapter.setEmptyView(createErrorView(hint = throwable?.msg ?: "未知错误"))
        } else {
            mSmartRefreshLayout.finishRefresh((true))
        }
        return status
    }

    private fun responseStatus2LiveData(status: Status, throwable: Throwable?): Status {
        if (status == Status.START) LoadingDialog.show(
            context = requireContext(), resId = R.layout.dialog_load_style_1
        ) else if (status == Status.FAILURE) {
            LoadingDialog.dismiss()
            toast(throwable?.msg ?: "未知错误")
        } else {
            LoadingDialog.dismiss()
        }
        return status
    }

    private fun createLoadingView(): View {
        return layoutInflater.inflate(R.layout.dialog_load_style_2, null)
    }


    private fun createErrorView(hint: String): View =
        TextView(requireContext()).apply {
            text = hint
            gravity = Gravity.CENTER
            textSize = 13f
            setTypeface(null, Typeface.BOLD)
            setTextColor(ColorUtils.getColor(R.color.FF_666666))
        }

    private fun createFooterView(): View =
        TextView(requireContext()).apply {
            layoutParams = FrameLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                ConvertUtils.dp2px(30f)
            )
            gravity = Gravity.CENTER
            textSize = 13f
            text = "没有更多数据"
            setTypeface(null, Typeface.BOLD)
            setTextColor(ColorUtils.getColor(R.color.FF_CCCCCC))
        }
}